package Plan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class GamePanel extends JPanel implements Runnable {
    private Player player;
    private ArrayList<Enemy> enemies;
    private ArrayList<Bullet> bullets;
    private Thread gameThread;
    private boolean running;
    private Random random;
    private int score;
    private Image backgroundImage;
    
    public GamePanel() {
        setPreferredSize(new Dimension(800, 600));
        setBackground(Color.BLACK);
        setFocusable(true);
        try {
            String imagePath = new java.io.File("background.png").getAbsolutePath();
            System.out.println("尝试加载背景图片路径: " + imagePath);
            backgroundImage = new ImageIcon(imagePath).getImage();
            if (backgroundImage == null) {
                System.out.println("背景图片加载失败，请检查文件是否存在");
            }
        } catch (Exception e) {
            System.out.println("无法加载背景图片: " + e.getMessage());
            e.printStackTrace();
        }
        
        player = new Player(400, 500);
        enemies = new ArrayList<>();
        bullets = new ArrayList<>();
        random = new Random();
        score = 0;
        
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                player.keyPressed(e);
                if (e.getKeyCode() == KeyEvent.VK_R && !running) {
                    resetGame();
                    startGame();
                }
            }
            
            @Override
            public void keyReleased(KeyEvent e) {
                player.keyReleased(e);
            }
        });
    }
    
    public void startGame() {
        running = true;
        gameThread = new Thread(this);
        gameThread.start();
    }
    
    private void resetGame() {
        player = new Player(400, 500);
        enemies.clear();
        bullets.clear();
        score = 0;
    }
    
    @Override
    public void run() {
        long lastTime = System.nanoTime();
        double nsPerTick = 1000000000.0 / 60.0;
        double delta = 0;
        
        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / nsPerTick;
            lastTime = now;
            
            while (delta >= 1) {
                update();
                delta--;
            }
            
            repaint();
            
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    private void update() {
        player.update();
        
        // 检查玩家是否发射子弹
        Bullet newBullet = player.fire();
        if (newBullet != null) {
            bullets.add(newBullet);
        }
        
        // 生成敌机
        if (random.nextInt(100) < 2) {
            enemies.add(new Enemy(random.nextInt(750), -50));
        }
        
        // 更新子弹
        for (int i = 0; i < bullets.size(); i++) {
            Bullet bullet = bullets.get(i);
            bullet.update();
            
            if (bullet.getY() < 0) {
                bullets.remove(i);
                i--;
            }
        }
        
        // 更新敌机
        for (int i = 0; i < enemies.size(); i++) {
            Enemy enemy = enemies.get(i);
            enemy.update();
            
            if (enemy.getY() > 600) {
                enemies.remove(i);
                i--;
                continue;
            }
            
            // 碰撞检测
            Rectangle playerRect = player.getBounds();
            Rectangle enemyRect = enemy.getBounds();
            
            if (playerRect.intersects(enemyRect)) {
                running = false;
                break;
            }
            
            for (int j = 0; j < bullets.size(); j++) {
                Bullet bullet = bullets.get(j);
                Rectangle bulletRect = bullet.getBounds();
                
                if (bulletRect.intersects(enemyRect)) {
                    enemies.remove(i);
                    bullets.remove(j);
                    score += 10;
                    i--;
                    break;
                }
            }
        }
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImage != null) {
            g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
        }
        
        if (running) {
            player.draw(g);
            
            for (Enemy enemy : enemies) {
                enemy.draw(g);
            }
            
            for (Bullet bullet : bullets) {
                bullet.draw(g);
            }
            
            g.setColor(Color.WHITE);
            g.drawString("得分: " + score, 20, 20);
        } else {
            // 死亡界面
            g.setColor(new Color(0, 0, 0, 150));
            g.fillRect(0, 0, getWidth(), getHeight());
            
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑", Font.BOLD, 50));
            String gameOver = "游戏结束";
            g.drawString(gameOver, getWidth()/2 - g.getFontMetrics().stringWidth(gameOver)/2, getHeight()/2 - 50);
            
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
            String finalScore = "最终得分: " + score;
            g.drawString(finalScore, getWidth()/2 - g.getFontMetrics().stringWidth(finalScore)/2, getHeight()/2 + 20);
            
            g.setColor(Color.GREEN);
            g.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            String restart = "按R键重新开始";
            g.drawString(restart, getWidth()/2 - g.getFontMetrics().stringWidth(restart)/2, getHeight()/2 + 70);
        }
    }
}